#include <iostream>
#include <memory>

using std::cout;
using std::endl;
using std::shared_ptr;

class Point
{
public:
    Point(int ix = 0, int iy = 0)
    : _ix(ix)
    , _iy(iy)
    {
        cout << "Point(int = 0, int = 0)" << endl;
    }

    void print() const
    {
        cout <<"(" << _ix
             << ", " << _iy
             << ")" << endl;
    }

    ~Point()
    {
        cout << "~Point()" << endl;
    }

    friend std::ostream &operator<<(std::ostream &os, const Point &rhs);
private:
    int _ix;
    int _iy;
};

std::ostream &operator<<(std::ostream &os, const Point &rhs)
{
    os <<"(" << rhs._ix
       << ", " << rhs._iy
       << ")";

    return os;

}

//问题的原因在于：使用了不同的智能指针托管了同一个裸指针
//（同一个资源），当智能指针销毁的时候，会有分别回收
void test()
{
    //sp与sp2都托管了裸指针pt，也就两个智能指针sp与sp2
    //都托管了同一个堆空间,每个智能指针销毁的时候，都会
    //回收堆空间
    Point *pt = new Point(1, 2);
    shared_ptr<Point> sp(pt);
    /* shared_ptr<Point> sp2(sp);//ok,增加引用计数 */
    shared_ptr<Point> sp2(pt);
    sp->print();
    sp2->print();
}

void test2()
{
    shared_ptr<Point> sp(new Point(1, 2));
    sp->print();

    cout << endl;
    shared_ptr<Point> sp2(new Point(3, 4));
    sp2->print();

    cout << endl <<"------" << endl;
    sp.reset(sp2.get());//隐蔽一些
    cout << "sp.print() = ";
    sp->print();
    cout << "sp2.print() = ";
    sp2->print();
}

int main(int argc, char *argv[])
{
    /* test(); */
    test2();
    return 0;
}

